<!--百度相关界面-->
<template>
  <baidu-map :center="center" :zoom="zoom"
    style="width: 76%;height: calc(100% + 0px); float:right;position:absolute;bottom:0;right:0;background-color: transparent;"
    :scroll-wheel-zoom="true" @ready="handleReady">
    <bm-navigation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" v-if="isShowNavigation"></bm-navigation>
    <!--地图类型控件-->
    <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_SATELLITE_MAP','BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_RIGHT"
      v-if="isShowMapType"></bm-map-type>
    <!--绘画点  :offset="{width:0,height:0}"  -->
    <bm-marker v-if="isShowMarker" :icon="item.markImage" :position="item.position" :dragging="item.dragging"
      @click="handleInfoWindowOpen(item)" animation="BMAP_ANIMATION_DROP" v-for="item in listMarkerInfo" :key="item.id">
      <bm-label :content="item.nickName+'('+item.id%1000000+')'"
        :labelStyle="{color: '#fff', fontSize : '16px',background:'rgba(0, 0, 0, 0.8)',borderColor:'rgba(255, 0, 0)',border :'1'}"
        :offset="{width: -45,height:-25 }" />
      <bm-info-window :show="item.isShow" @close="handleInfoWindowClose(item)" @open="handleInfoWindowOpen(item)">
        <div v-html="item.contents"></div>
      </bm-info-window>
    </bm-marker>
  </baidu-map>
</template>

<script>
  //百度地图相关文档  https://dafrok.github.io/vue-baidu-map/#/zh/start/base
  import Vue from 'vue'
  import axios from 'axios'

  import {
    BmlLushu
  } from 'vue-baidu-map'
  import {
    getGuid16
  } from "@/libs/util"
  export default {
    name: "vueMap",
    data() {
      return {
        WBMap: '', //百度地图核心类
        Wmap: '', //百度地图实例
        style: {
          width: '100%',
          height: '100%'
        },
        pcLocation:{
          lng: 118.60036234,
          lat: 39.907899
        },
        center: {
          lng: 118.60036234,
          lat: 39.907899
        }, //北京天安门为初始化中心点
        zoom: 20, //压缩比例
        isShowGeolocation: true, //是否显示定位信息
        isShowScale: true, //是否在右上角显示比例尺控件
        isShowNavigation: true, //是否在右上角显示缩放控件
        isShowMapType: true, //是否显示 地图类型控件
        isShowOverviewMap: true, //是否显示 缩略图控件
        isShowMarker: true, //是否显示 绘画点控件
        speed: 0,
        mapStyle: { //地图主题颜色
          styleJson: [{
              "featureType": "all",
              "elementType": "geometry",
              "stylers": {
                "hue": "#007fff",
                "saturation": 89
              }
            },
            {
              "featureType": "water",
              "elementType": "all",
              "stylers": {
                "color": "#ffffff"
              }
            }
          ]
        },
        listMarkerInfo: [], //绘画点
        memberMakers: [], //用户标记存储
        lushuPlay: false, //轨迹回放功能 是否播放
        lushuPath: [], //轨迹回放功能 运动轨迹
        lushuInfoWindow: '', //显示头部信息
        startMark: { //起始坐标
          lng: '',
          lat: '',
        },
        endMark: { //结束坐标
          lng: '',
          lat: '',
        },
        startIcon: {
          url: '/img/track_start.png',
          size: {
            width: 48,
            height: 48
          }
        },
        endIcon: {
          url: '/img/track_end.png',
          size: {
            width: 48,
            height: 48
          }
        },
        playIcon: {
          url: '/img/track_person.png',
          size: {
            width: 64,
            height: 64
          }
        },
        polygonPath: {
          editing: false,
          paths: [] // 绘制完成后的经纬度，其实是在画的时候动态push的，因为在点击的时候触发了 paintPolygon 函数
        },
        circlePath: {
          center: {
            lng: 116.404,
            lat: 39.915
          },
          radius: 5000
        },
        currentModel: 0,
        isStartMarkeModel: false,
        isStartCircleModel: false,
        isStartCircleEdit: true,
        geo: null,
      }
    },
    components: {
      BmlLushu
    },
    methods: {
      /**
       * 地图组件渲染完毕时触发，返回一个百度地图的核心类和地图实例。
       */
       handleReady({
        BMap,
        map
      }) {
        let that = this;
        that.WBMap = BMap;
        that.Wmap = map;
        map.enableScrollWheelZoom(true)
        that.zoom = 15
        that.Wmap.setMapType(BMAP_HYBRID_MAP); //混合地图
        let geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(async function (r) {
          that.pcLocation = r.point // 设置地图定位中心点
          let _address = await that.getAddress(that.pcLocation.lng, that.pcLocation.lat);
          that.pcLocation.address = _address
          //通知主页当前位置
           // Vue.prototype.$handleOperateMethods("weather", {
           //     lat:that.center.lat,
           //     lng:that.center.lng,
           //     city:_address
           // });


        }, {
          enableHighAccuracy: true
        })
        that.geo = new BMap.Geocoder();
      },
      //------------------------------封装方法供外部调用 start-------------------------------------
      /**
       * maker绘画
       * @param points 绘画的点
       * @param label 显示的文本内容
       * @param icons icon图片链接
       */
      handleSetMarker(data) {
        this.zoom = 20
        let temp = {
          id: data.uid,
          nickName: data.nickName,
          markImage: {
            url: '/p2pweb/img/marker-online.png',
            size: {
              width: 64,
              height: 64
            }
          },
          dragging: false,
          position: {
            lat: data.lat,
            lng: data.lng
          },
          contents: `<p style='margin:5px'>${this.lang.map.map_nick}${data.nickName}</p>
                        <p style='margin:5px'>${this.lang.map.map_id}${data.uid%1000000}</p>
                        <p style=';margin:5px'>${this.lang.map.map_time}${data.time}</p>
                        <p style=';margin:5px'>${this.lang.map.map_lat}${data.lat}</p>
                        <p style=';margin:5px'>${this.lang.map.map_lng}${data.lng}</p>
                        <p style=';margin:5px'>${this.lang.map.map_address}${data.address}</p>
                      `,
          isShow: true, //是否显示infoWindow
        };
        this.listMarkerInfo = []
        this.listMarkerInfo.push(temp);
      },
      /**
       * maker绘画
       * @param points 绘画的点
       * @param label 显示的文本内容
       * @param icons icon图片链接
       */
      handleSetGroupMarker(data) {
        let isOffline = (data.channel === -1 || data.channel === "-1")
        let temp = {
          id: data.uid,
          nickName: data.nickName,
          markImage: isOffline ? {
            url: '/img/marker-offline.png',
            size: {
              width: 64,
              height: 64
            }
          } : {
            url: '/img/marker-online.png',
            size: {
              width: 64,
              height: 64
            }
          },
          dragging: false,
          position: {
            lat: data.lat,
            lng: data.lng
          },
          contents: ` <p style='margin:5px'>${this.lang.map.map_nick}${data.nickName}</p>
                        <p style='margin:5px'>${this.lang.map.map_id}${data.uid%1000000}</p>
                        <p style=';margin:5px'>${this.lang.map.map_time}${data.time}</p>
                        <p style=';margin:5px'>${this.lang.map.map_lat}${data.lat}</p>
                        <p style=';margin:5px'>${this.lang.map.map_lng}${data.lng}</p>
                        <p style=';margin:5px'>${this.lang.map.map_address}${data.address}</p>
                      `,
          isShow: false, //是否显示infoWindow
        };
        this.listMarkerInfo.push(temp);
      },
      /**
       * maker SOS 绘画
       * @param points 绘画的点
       * @param label 显示的文本内容
       * @param icons icon图片链接
       */
      handleSetSosMarker(data) {
        let temp = {
          id: data.uid,
          nickName: data.nickName,
          markImage: {
            url: '/img/warning.png',
            size: {
              width: 64,
              height: 64
            }
          },
          dragging: false,
          position: {
            lat: data.lat,
            lng: data.lng
          },
          contents: ` <p style='margin:5px'>${this.lang.map.map_nick}${data.nickName}</p>
                        <p style='margin:5px'>${this.lang.map.map_id}${data.uid%1000000}</p>
                        <p style=';margin:5px'>${this.lang.map.map_time}${data.time}</p>
                        <p style=';margin:5px'>${this.lang.map.map_lat}${data.lat}</p>
                        <p style=';margin:5px'>${this.lang.map.map_lng}${data.lng}</p>
                        <p style=';margin:5px'>${this.lang.map.map_address}${data.address}</p>
                      `,
          isShow: true, //是否显示infoWindow
        };
        this.listMarkerInfo.push(temp);
      },
      /**
       * 坐标系转换 GPS坐标(WGS84)转换百度坐标(BD09)
       * */
      async mGeoconv(lon, lat) {

        let that = this;
        let queryStr = `http://api.map.baidu.com/geoconv/v1/?coords=${lon},${lat}&from=1&to=5&ak=${this.$mapKey}`
        let data = {}
        await axios
          .get(queryStr)
          .then(response => {
            data.x = response.data.result[0].x
            data.y = response.data.result[0].y
            // console.log()
            //  console.log(response.data.result[0].y)
          })
          .catch(function(error) { // 请求失败处理
            console.log(error);
          });
        return data;

      },
      getAddress(lng, lat) {
        let that = this;
        return new Promise((resolve, reject) => {
          let city = ""
          const point = new BMap.Point(lng, lat);
          that.geo.getLocation(point, (res) => {
            let _add = res.address
            if (res.surroundingPois.length > 0) {
              _add = _add + res.surroundingPois[0].title
            }
            city = _add;
            return resolve(city);
          })
        })
      },
      getAddressOfCity(lng, lat) {
        let that = this;
        return new Promise((resolve, reject) => {
          let city = ""
          const point = new BMap.Point(lng, lat);
          that.geo.getLocation(point, (res) => {
            console.log(res)
            let _addCity = res.addressComponents.city

            return resolve(_addCity);
          })
        })
      },
      //----------------------------------封装方法供外部调用 end------------------------------------------------
      /**
       * maker标注
       * @param points 绘画的点
       * @param label 显示的文本内容
       * @param icons icon图片链接
       */
      handleSetCustomeMarker(points, label) {
        let temp = {
          id: getGuid16(),
          dragging: false,
          position: points,
          contents: `<p style='text-align:center;margin:5px'>${label}</p>
                        <p style='margin:5px'>标注主题：测试标注</p>
                        <p style=';margin:5px'>经    度：${points.lat}</p>
                        <p style=';margin:5px'>纬    度：${points.lng}</p>
                        <p style=';margin:5px'>内容：泉州市优度智捷科技有限公司</p>
                      `,
          isShow: true, //是否显示infoWindow
        };
        this.listMarkerInfo.push(temp);
      },
      /**
       * 关闭弹窗
       * @param item 当前点击的元素
       */
      handleInfoWindowClose(item) {
        item.isShow = false;
      },
      /**
       * 显示弹窗
       * @param item 当前点击的元素
       */
      handleInfoWindowOpen(item) {
        item.isShow = true;
      },
      /**
       * 标志一个成员
       */
      doMaker(data) {
        let that = this
        //alert(data)
        that.center = {
          lng: data.lng,
          lat: data.lat
        }
        that.handleSetMarker(data);

      },
      /**
       * 标志群组成员
       */
      doGroupMaker(data) {
        let that = this
        if (data.length > 80) {
          that.zoom = 20
        } else {
          that.zoom = 15
        }
        this.listMarkerInfo = []
        var i = 0;
        for (let item of data) {
          setTimeout(async function() {
            if (item.address.length === 0) {
              let data = await that.mGeoconv(item.lng, item.lat)
              item.lng = data.x
              item.lat = data.y
              let _address = await that.getAddress(item.lng, item.lat);
              item.address = _address
            }
            that.handleSetGroupMarker(item);
          }, i * 100);
          i++
        }

        that.center = {
          lng: data[0].lng,
          lat: data[0].lat
        }

      },
      /**
       * 标志SOS
       */
      doSosMaker(data) {
        let that = this
        console.log(data)
        that.zoom = 15
        this.listMarkerInfo = []
        that.handleSetSosMarker(data);
        that.center = {
          lng: data.lng,
          lat: data.lat
        }

      },
      changeCenter(uid) {
        let that = this
        for (let item of that.listMarkerInfo) {
          if (parseInt(item.id) === parseInt(uid)) {
            that.center = item.position
            that.zoom = 20
            return
          }
        }
      }
    },
    mounted() {
      //注册全局的地址信息
      Vue.prototype.$map = this;
    }
  }
</script>

<style scoped>

</style>
